<template>
  <div class="page">
    <!-- 顶部操作按钮 -->
    <el-form :inline="true" :model="queryParams">
      <el-form-item>
        <el-button type="primary" :icon="Plus" @click="add">
          新增
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :icon="Search" @click="initData">
          刷新
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="EditPen" @click="setting">
          设置
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="EditPen" @click="logPage">
          日志
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 任务列表 -->
    <el-table :data="data" :border="true" @selection-change="handleSelectionChange">
      <el-table-column label="序号" prop="oid" />
      <el-table-column label="ID" prop="id" />
      <el-table-column label="时间" prop="timeRange">
        <template #default="scope">
          <div class="column">
            <span>开始时间：{{ parseTime(scope.row.timeRange[0]) }}</span>
            <span>结束时间：{{ parseTime(scope.row.timeRange[1]) }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="deleteTime" />
      <el-table-column label="开始-结束小时" prop="startHour">
        <template #default="scope">
          <div class="column">
            <span>开始小时：{{ (scope.row.startHour) }}</span>
            <span>结束小时：{{ (scope.row.endHour) }}</span>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="操作" prop="timeRange">
        <template #default="scope">
          <el-button type="danger" size="mini" @click="del(scope.$index)">删除</el-button>
          <el-button type="primary" size="mini" @click="edit(scope.$index)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="bottom">
      <el-button type="primary" @click="run" v-loading="loading">手动执行</el-button>
    </div>

    <!-- 表单区 -->
    <el-dialog v-model="dialogFormVisible" title="添加任务">
      <el-form :model="form">
        <el-form-item :required="true">
          <el-button type="primary" @click="pushId">添加</el-button>
        </el-form-item>
        <!-- id -->
        <el-form-item label="ID" v-for="(item, index) in form.id" :key="item" :label-width="formLabelWidth">
          <el-tag class="ml-2" closable @close="handleClose(index)">{{ item }}</el-tag>
        </el-form-item>
        <!-- 时间范围 -->
        <el-form-item :required="true" label="时间范围" :label-width="formLabelWidth">
          <el-date-picker v-model="form.timeRange" type="datetimerange" range-separator="至" format="YYYY/MM/DD HH"
            start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>

        <!-- 小时范围 -->
        <el-form-item label="小时范围" :label-width="formLabelWidth">
          <div class="hour">
            <el-input v-model="form.startHour" :min="1" :max="23" placeholder="请输入开始小时"></el-input>
            <el-input v-model="form.endHour" :min="1" :max="23" placeholder="请输入结束小时"></el-input>
          </div>
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="save">
            保存数据
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { Plus, Search, EditPen } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { onMounted, onUnmounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";
import { useRouter } from "vue-router";

const queryParams = reactive({
  oid: "",
});

const multipleSelection = ref([]);

const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};

const router = useRouter();
const setting = () => {
  router.push({ name: "setting" });
};

const logPage = () => {
  router.push({ name: "log" });
}

const loading = ref(false);

const mode = ref("add");
const editIndex = ref(-1);

const handleClose = (index) => {
  form.id.splice(index, 1);
};

const add = () => {
  dialogFormVisible.value = true;
  mode.value = "add";
};

const del = async (index) => {
  let id = data.value[index].oid;
  let res = await axios.request({
    url: "http://127.0.0.1:3000/order/" + id,
    method: "delete",
  });

  if (res.data.code == 200) {
    ElMessage.success("删除成功");
    initData();
  }
};

const edit = async (index) => {
  dialogFormVisible.value = true;
  editIndex.value = index;
  mode.value = "edit";

  form.id = data.value[index].id;
  form.timeRange = data.value[index].timeRange;
  form.startHour = data.value[index].startHour;
  form.endHour = data.value[index].endHour;
};

const pushId = () => {
  ElMessageBox.prompt("请输入id", "Tip", {
    confirmButtonText: "OK",
    cancelButtonText: "Cancel",
  })
    .then(({ value }) => {
      form.id.push(value);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消",
      });
    });
};

const save = async () => {
  let item = JSON.parse(JSON.stringify(form));
  if (mode.value == "add") {
    let res = await axios.request({
      url: "http://127.0.0.1:3000/order",
      method: "post",
      data: {
        order_id: item.id.join(","),
        startTime: item.timeRange[0],
        endTime: item.timeRange[1],
        startHour: item.startHour,
        endHour: item.endHour,
      },
    });

    if (res.data.code == 200) {
      ElMessage.success("添加成功");
    }

    dialogFormVisible.value = false;
    form.id = [];
    initData();
  } else {
    let res = await axios.request({
      url: "http://127.0.0.1:3000/order/" + data.value[editIndex.value].oid,
      method: "patch",
      data: {
        order_id: item.id.join(","),
        startTime: item.timeRange[0],
        endTime: item.timeRange[1],
        startHour: item.startHour,
        endHour: item.endHour,
      },
    });

    if (res.data.code == 200) {
      ElMessage.success("添加成功");
    }

    dialogFormVisible.value = false;
    form.id = [];
    initData();
  }
};

const data = ref([]);

const parseTime = (value) => {
  return dayjs(value).format("YYYY-MM-DD HH");
};

const initData = async () => {
  let res = await axios.request({
    url: "http://127.0.0.1:3000/order",
    method: "get",
  });

  if (res.data.code == 200) {
    data.value = res.data.data.map((item) => {
      return {
        oid: item.id,
        id: item.order_id.split(","),
        timeRange: [item.startTime, item.endTime],
        deleteTime: item.deleteTime ? '已执行' : '运行中',
        startHour: item.startHour,
        endHour: item.endHour,
      };
    });
  }
};

// 新增表单
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = reactive({
  id: [],
  timeRange: "",
});

const run = () => {
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 5000)

  axios.request({
    url: "http://127.0.0.1:3000/order/test",
    method: "get",
  });
};

/**
 * 页面加载完成时获取数据
 */
onMounted(() => {
  initData();
});

onUnmounted(() => { });
</script>
<style lang="scss" scoped>
.page {
  flex: 1;
  width: 100vw;
  min-height: 100vh;
  background-color: #f7f7f7;

  display: flex;
  flex-flow: column nowrap;
  justify-content: flex-start;
  align-items: flex-start;
  box-sizing: border-box;

  overflow-x: hidden;
  overflow-y: auto;

  padding: 24px;
  padding-bottom: 50px;

  .list {
    width: 100%;
  }
}

.column {
  width: 100%;
  height: 60px;
  line-height: 30rpx;

  display: flex;
  flex-flow: column nowrap;
  justify-content: space-around;
  align-items: center;
}

.bottom {
  width: 100vw;
  height: 50px;
  background-color: #ffffff;
  position: fixed;
  bottom: 0;
  left: 0;

  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
  align-items: center;

  box-sizing: border-box;
  padding: 0 24px;
}

.hour {
  width: 300px;

  display: flex;
  flex-flow: row nowrap;
  justify-content: space-evenly;
  align-items: center;
  gap: 20px;
}
</style>
